import fs from 'node:fs'
import { execa } from 'execa'

const targets = fs.readdirSync('packages').filter(file => {
  if (fs.statSync(`packages/${file}`).isDirectory()) {
    return true
  }

  return false
})


async function build(target) {

  fs.rmSync(`packages/${target}/dist/`, { recursive: true, force: true }) // 删除 dist 目录下的所有文件
  
  execa(`rollup`, ['-c', '--environment', `TARGET:${target}`], {
    stdio: 'inherit', // 子进程打包的信息，在父进程中打印
  })
  
}

function runParallel(targets, iteratorFn) {
  const res = []

  for (let i = 0; i < targets.length; i++) {
    const p = Promise.resolve().then(() => iteratorFn(targets[i]))
    res.push(p)
  }

  return Promise.all(res)
}

runParallel(targets, build)
